<template>
  <v-container>
    <v-container
      v-show="!isLogin"
    >
      <v-card>
        <v-toolbar
          color="primary"
          dark
        >管理员登录</v-toolbar>
        <v-text-field
          outlined
          label="管理员id"
          v-model="cid"
        ></v-text-field>
        <v-text-field
          outlined
          label="密码"
          v-model="cpwd"
        ></v-text-field>
        <v-card-actions class="justify-end">
          <v-btn
            text
            @click="controlerLogin"
          >登录</v-btn>
        </v-card-actions>
      </v-card>
    </v-container>
    <v-container
      v-show="isLogin"
    >
      <v-row>
      <v-app-bar
        elevation="0"
        color="#008792"
      >
        <span class="title">内容管理系统</span>
      </v-app-bar>
    </v-row>
      <v-row
        justify="start"
      >
        <v-col
          cols="2"
          style="background-color: white"
        >
          <v-card
            tile
            elevation="0"
          >
            <v-list
              flat
            >
              <v-subheader>管理选项</v-subheader>
              <v-list-item-group
                v-model="selectedItem"
                color="primary"
              >
                <v-list-item
                  v-for="(item, i) in items"
                  :key="i"
                  @click="getInfo(i)"
                >
                  <v-list-item-icon>
                    <v-icon v-text="item.icon"></v-icon>
                  </v-list-item-icon>
                  <v-list-item-content>
                    <v-list-item-title v-text="item.text"></v-list-item-title>
                  </v-list-item-content>
                </v-list-item>
              </v-list-item-group>
            </v-list>
          </v-card>
        </v-col>
        <v-col
          cols="10"
        >
          <div
            v-show="showList[0]"
          >
            <v-card
              class="info-head"
            >
              <v-row>
                <v-col>
                  <v-dialog
                    transition="dialog-bottom-transition"
                    max-width="600"
                  >
                    <template v-slot:activator="{on, attrs}">
                      <v-btn
                        elevation="2"
                        v-bind="attrs"
                        v-on="on"
                      >添加用户</v-btn>
                    </template>
                    <template v-slot:default="dialog">
                      <v-card>
                        <v-toolbar
                          color="primary"
                          dark
                        >添加用户{{ newInfo }}</v-toolbar>
                        <v-text-field
                          v-model="newUserName"
                          outlined
                          label="新用户名"
                        ></v-text-field>
                        <v-text-field
                          v-model="newUserPass"
                          outlined
                          label="新密码"
                        ></v-text-field>
                        <v-card-actions class="justify-end">
                          <v-btn
                            text
                            @click="addUser(); dialog.value = false"
                          >添加</v-btn>
                          <v-btn
                            text
                            @click="dialog.value = false"
                          >关闭</v-btn>
                        </v-card-actions>
                      </v-card>
                    </template>
                  </v-dialog>
                </v-col>
              </v-row>
            </v-card>
            <v-card
              class="info-head"
            >
              <v-row>
                <v-col
                  v-for="(value, idx) in infoHeader"
                  :key="idx"
                >
                  <span>{{ value }}</span>
                </v-col>
              </v-row>
            </v-card>
            <v-card
              v-for="(value, idx) in userInfo"
              :key="idx"
              class="info"
            >
              <v-row>
                <v-col
                  v-for="(val, keyVal, idx) in value"
                  :key="idx"
                ><span>{{ val }}</span></v-col>
                <v-col>
                  <v-dialog
                    transition="dialog-bottom-transition"
                    max-width="600"
                  >
                    <template v-slot:activator="{on, attrs}">
                      <v-btn
                        elevation="2"
                        v-bind="attrs"
                        v-on="on"
                      >修改信息</v-btn>
                    </template>
                    <template v-slot:default="dialog">
                      <v-card>
                        <v-toolbar
                          color="primary"
                          dark
                        >修改信息{{ newInfo }}</v-toolbar>
                        <v-text-field
                          v-for="(val, key, idx) in value"
                          :key="idx"
                          :label="key"
                          :placeholder="val"
                          clearable
                          outlined
                          v-model="newInfo[key]"
                        ></v-text-field>
                        <v-card-actions class="justify-end">
                          <v-btn
                            text
                            @click="changeInfo(value, 0); dialog.value = false; newInfo = {}; getInfo(0)"
                          >提交</v-btn>
                          <v-btn
                            text
                            @click="dialog.value = false; newInfo = {}"
                          >关闭</v-btn>
                        </v-card-actions>
                      </v-card>
                    </template>
                  </v-dialog>
                  <v-dialog
                    transition="dialog-bottom-transition"
                    max-width="600"
                  >
                    <template v-slot:activator="{on, attrs}">
                      <v-btn
                        elevation="2"
                        v-bind="attrs"
                        v-on="on"
                      >删除用户</v-btn>
                    </template>
                    <template v-slot:default="dialog">
                      <v-card>
                        <v-toolbar
                          color="primary"
                          dark
                        >删除信息</v-toolbar>
                        <p>用户名：{{ value.uname }}</p>
                        <p>密码：{{ value.password }}</p>
                        <v-card-actions class="justify-end">
                          <v-btn
                            text
                            @click="deleteUser(value, 0);dialog.value = false; newInfo = {};getInfo(0)"
                          >提交</v-btn>
                          <v-btn
                            text
                            @click="dialog.value = false; newInfo = {}"
                          >关闭</v-btn>
                        </v-card-actions>
                      </v-card>
                    </template>
                  </v-dialog>
                </v-col>
              </v-row>
            </v-card>
          </div>
          <div
            v-show="showList[1]"
          >
            <v-card
              class="info-head"
            >
              <v-row>
                <v-col
                  v-for="(value, idx) in infoHeader"
                  :key="idx"
                >
                  <span>{{ value }}</span>
                </v-col>
              </v-row>
            </v-card>
            <v-card
              v-for="(value, idx) in logInfo"
              :key="idx"
              class="info"
            >
              <v-row>
                <v-col><span>{{ value.uid }}</span></v-col>
                <v-col><span>{{ value.op }}</span></v-col>
                <v-col>
                <span>
                  {{ new Date(value.time).getFullYear() }}年
                  {{ new Date(value.time).getMonth() + 1 }}月
                  {{ new Date(value.time).getDate() }}日
                  {{ new Date(value.time).getHours() }}时
                  {{ new Date(value.time).getMinutes() }}分
                  {{ new Date(value.time).getSeconds() }}秒
                </span>
                </v-col>
                <v-col>
                  <v-dialog
                    transition="dialog-bottom-transition"
                    max-width="600"
                  >
                    <template v-slot:activator="{on, attrs}">
                      <v-btn
                        elevation="2"
                        v-bind="attrs"
                        v-on="on"
                      >删除信息</v-btn>
                    </template>
                    <template v-slot:default="dialog">
                      <v-card>
                        <v-toolbar
                          color="primary"
                          dark
                        >删除信息</v-toolbar>
                        <p>用户id: {{ value.uid }}</p>
                        <p>用户操作：{{ value.op }}</p>
                        <p>
                          时间: {{ new Date(value.time).getFullYear() }}年
                          {{ new Date(value.time).getMonth() + 1 }}月
                          {{ new Date(value.time).getDate() }}日
                          {{ new Date(value.time).getHours() }}时
                          {{ new Date(value.time).getMinutes() }}分
                          {{ new Date(value.time).getSeconds() }}秒
                        </p>
                        <v-card-actions class="justify-end">
                          <v-btn
                            text
                            @click="changeInfo(value, 1); dialog.value = false; newInfo = {}; getInfo(1)"
                          >删除</v-btn>
                          <v-btn
                            text
                            @click="dialog.value = false; newInfo = {}"
                          >关闭</v-btn>
                        </v-card-actions>
                      </v-card>
                    </template>
                  </v-dialog>
                </v-col>
              </v-row>
            </v-card>
          </div>
          <div
            v-show="showList[2]"
          >
            <v-card
              class="info-head"
            >
              <v-row>
                <v-col
                  v-for="(value, idx) in infoHeader"
                  :key="idx"
                >
                  <span>{{ value }}</span>
                </v-col>
              </v-row>
            </v-card>
            <v-card
              v-for="(value, idx) in contentInfo"
              :key="idx"
              class="info"
            >
              <v-row>
                <v-col><span>{{ value.name }}</span></v-col>
                <v-col><span>{{ value.content }}</span></v-col>
                <v-col>
                  <v-img
                    :src="value.pic"
                    max-width="100px"
                    max-height="100px"
                  ></v-img>
                </v-col>
                <v-col>
                  <v-dialog
                    transition="dialog-bottom-transition"
                    max-width="600"
                  >
                    <template v-slot:activator="{on, attrs}">
                      <v-btn
                        elevation="2"
                        v-bind="attrs"
                        v-on="on"
                      >修改信息</v-btn>
                    </template>
                    <template v-slot:default="dialog">
                      <v-card>
                        <v-toolbar
                          color="primary"
                          dark
                        >修改信息{{ newInfo }}</v-toolbar>
                        <p>词条名: {{ value.name }}</p>
                        <p>词条内容：{{ value.content }}</p>
                        <v-img>词条配图：{{ value.pic }}</v-img>
                        <v-card-actions class="justify-end">
                          <v-btn
                            text
                            @click="dialog.value = false; newInfo = {}"
                          >修改</v-btn>
                          <v-btn
                            text
                            @click="dialog.value = false; newInfo = {}"
                          >关闭</v-btn>
                        </v-card-actions>
                      </v-card>
                    </template>
                  </v-dialog>
                </v-col>
              </v-row>
            </v-card>
          </div>
          <div
            v-show="showList[3]"
          >
            <v-card
              class="info-head"
            >
              <v-row>
                <v-col
                  v-for="(value, idx) in infoHeader"
                  :key="idx"
                >
                  <span>{{ value }}</span>
                </v-col>
              </v-row>
            </v-card>
            <v-card
              v-for="(value, idx) in scoreInfo"
              :key="idx"
              class="info"
            >
              <v-row>
                <v-col><span>{{ value.uname }}</span></v-col>
                <v-col><span>{{ value.one }}</span></v-col>
                <v-col><span>{{ value.two }}</span></v-col>
                <v-col>
                  <v-dialog
                    transition="dialog-bottom-transition"
                    max-width="600"
                  >
                    <template v-slot:activator="{on, attrs}">
                      <v-btn
                        elevation="2"
                        v-bind="attrs"
                        v-on="on"
                      >修改信息</v-btn>
                    </template>
                    <template v-slot:default="dialog">
                      <v-card>
                        <v-toolbar
                          color="primary"
                          dark
                        >修改信息</v-toolbar>
                        <p>玩家名: {{ value.uname }}</p>
                        <p>第一首歌的成绩：{{ value.one }}</p>
                        <p>第二首歌的成绩：{{ value.two }}</p>
                        <v-card-actions class="justify-end">
                          <v-btn
                            text
                            @click="dialog.value = false; newInfo = {}"
                          >修改</v-btn>
                          <v-btn
                            text
                            @click="dialog.value = false; newInfo = {}"
                          >关闭</v-btn>
                        </v-card-actions>
                      </v-card>
                    </template>
                  </v-dialog>
                </v-col>
              </v-row>
            </v-card>
          </div>
        </v-col>
      </v-row>
    </v-container>
  </v-container>
</template>

<script>
export default {
  name: 'ControlPage',
  data: () => ({
    isLogin: false,
    cid: '',
    cpwd: '',
    controlerId: '000001',
    selectedItem: 0,
    items: [
      { text: '用户管理', icon: 'mdi-account' },
      { text: '记录管理', icon: 'mdi-clock' },
      { text: '词条管理', icon: 'mdi-flag' },
      { text: '玩家记录', icon: 'mdi-license' }
    ],
    showList: [true, false, false, false],
    infoHeader: [],
    userInfo: [],
    newUserName: '',
    newUserPass: '',
    logInfo: [],
    contentInfo: [],
    scoreInfo: [],
    newInfo: {}
  }),
  mounted () {
    this.getInfo(this.selectedItem)
  },
  methods: {
    getInfo: function (idx) {
      for (let i = 0; i < this.showList.length; i++) {
        this.showList[i] = false
      }
      this.showList[idx] = true
      // eslint-disable-next-line no-undef
      const app = tcb.init({ env: 'rhythm-8gijcn1i263ac8ec' })

      const auth = app.auth()

      auth.anonymousAuthProvider().signIn() // 匿名登录，实际业务时根据需要进行调整
        .then(() => {
          console.log('数据库用户登录成功') // 登录成功
        }).catch(err => {
          console.log('数据库用户登录失败', err) // 登录失败
        })

      const db = app.database()

      this.infoHeader.splice(0, this.infoHeader.length)
      this.userInfo.splice(0, this.userInfo.length)
      this.logInfo.splice(0, this.logInfo.length)
      this.contentInfo.splice(0, this.contentInfo.length)
      this.scoreInfo.splice(0, this.scoreInfo.length)
      if (idx === 0) {
        this.infoHeader = ['用户', '密码', '操作']
        db.collection('user')
          .get()
          .then((res) => {
            for (let i = 0; i < res.data.length; i++) {
              this.userInfo.push({ uname: res.data[i].uname, password: res.data[i].password })
            }
          })
      } else {
        if (idx === 1) {
          this.infoHeader = ['用户id', '用户操作', '时间', '操作']
          db.collection('log')
            .get()
            .then((res) => {
              for (let i = 0; i < res.data.length; i++) {
                this.logInfo.push({ uid: res.data[i].uid, op: res.data[i].op, time: res.data[i].time })
              }
            })
        } else {
          if (idx === 2) {
            this.infoHeader = ['词条名称', '词条内容', '词条配图', '操作']
            db.collection('content')
              .get()
              .then((res) => {
                for (let i = 0; i < res.data.length; i++) {
                  this.contentInfo.push({ name: res.data[i].name, content: res.data[i].content, pic: res.data[i].pic })
                }
              })
          } else {
            if (idx === 3) {
              this.infoHeader = ['玩家名称', '第一首歌', '第二首歌', '操作']
              db.collection('score')
                .get()
                .then((res) => {
                  for (let i = 0; i < res.data.length; i++) {
                    this.scoreInfo.push({ uname: res.data[i].uname, one: res.data[i].one, two: res.data[i].two })
                  }
                })
            } else {
              console.log('sorry, this service does not open!')
            }
          }
        }
      }
    },
    changeInfo: function (val, idx) {
      const value = JSON.parse(JSON.stringify(val))
      if (this.newInfo !== {}) {
        // eslint-disable-next-line no-undef
        const app = tcb.init({ env: 'rhythm-8gijcn1i263ac8ec' })

        const auth = app.auth()

        auth.anonymousAuthProvider().signIn() // 匿名登录，实际业务时根据需要进行调整
          .then(() => {
            console.log('数据库用户登录成功') // 登录成功
          }).catch(err => {
            console.log('数据库用户登录失败', err) // 登录失败
          })

        const db = app.database()

        if (this.selectedItem === 0) {
          db.collection('user')
            .where({
              uname: value.uname
            })
            .update({
              uname: this.newInfo.uname,
              password: this.newInfo.password
            })
            .then((res) => {
              console.log(res)
              console.log('OK')
            })
          db.collection('log')
            .add({
              uid: this.controlerId,
              op: '修改玩家信息 -ou ' + value.uname + ' -op ' + value.password +
                ' -u ' + this.newInfo.uname + ' -p ' + this.newInfo.password,
              time: Date.now()
            })
        } else {
          if (this.selectedItem === 1) {
            db.collection('log')
              .where({
                uid: value.uid,
                op: value.op,
                time: value.time
              })
              .remove()
              .then((res) => {
                console.log(res)
                console.log('OK')
              })
          } else {
            console.log('sorry, this service does not open!')
          }
        }
      }
    },
    deleteUser: function (value, idx) {
      // eslint-disable-next-line no-undef
      const app = tcb.init({ env: 'rhythm-8gijcn1i263ac8ec' })

      const auth = app.auth()

      auth.anonymousAuthProvider().signIn() // 匿名登录，实际业务时根据需要进行调整
        .then(() => {
          console.log('数据库用户登录成功') // 登录成功
        }).catch(err => {
          console.log('数据库用户登录失败', err) // 登录失败
        })

      const db = app.database()
      db.collection('user')
        .where({
          uname: value.uname
        })
        .remove()
        .then((res) => {
          console.log(res)
          console.log('OK')
        })
      db.collection('log')
        .add({
          uid: this.controlerId,
          op: '删除用户信息 -u ' + value.uname + ' -p ' + value.password,
          time: Date.now()
        })
    },
    addUser: function () {
      // eslint-disable-next-line no-undef
      const app = tcb.init({ env: 'rhythm-8gijcn1i263ac8ec' })

      const auth = app.auth()

      auth.anonymousAuthProvider().signIn() // 匿名登录，实际业务时根据需要进行调整
        .then(() => {
          console.log('数据库用户登录成功') // 登录成功
        }).catch(err => {
          console.log('数据库用户登录失败', err) // 登录失败
        })

      const db = app.database()
      db.collection('user')
        .add({
          uname: this.newUserName,
          password: this.newUserPass
        })
        .then((res) => {
          console.log(res)
          console.log('OK')
        })
      db.collection('log')
        .add({
          uid: this.controlerId,
          op: '添加新用户 -u ' + this.newUserName + ' -p ' + this.newUserPass,
          time: Date.now()
        })
      this.getInfo(0)
    },
    controlerLogin: function () {
      // eslint-disable-next-line no-undef
      const app = tcb.init({ env: 'rhythm-8gijcn1i263ac8ec' })

      const auth = app.auth()

      auth.anonymousAuthProvider().signIn() // 匿名登录，实际业务时根据需要进行调整
        .then(() => {
          console.log('数据库用户登录成功') // 登录成功
        }).catch(err => {
          console.log('数据库用户登录失败', err) // 登录失败
        })

      const db = app.database()
      db.collection('controls')
        .where({
          cid: this.cid,
          cpass: this.cpwd
        })
        .get()
        .then((res) => {
          if (res.data.length > 0) {
            console.log('ok')
            this.isLogin = true
            this.controlerId = this.cid
            db.collection('log')
              .add({
                uid: this.controlerId,
                op: '管理员登录',
                time: Date.now()
              })
          }
        })
    }
  }
}
</script>

<style scoped>
.title {
  font-size: 28px;
}
.info {
  margin: 20px;
  height: 100px;
  background-color: #ffa78d;
}
.info-head {
  margin: 20px;
  height: 50px;
}
span {
  text-align: center;
}
</style>
